// pages/profile/profile.js
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');
const app = getApp();

Page({
  data: {
    // 用户编号
    userNum: null,
    
    // 用户资料
    userProfile: {},
    
    // 择偶标准
    matePreference: {},
    
    // 当前选中的Tab
    selectedTab: 'profile',
    
    // 今日送花状态
    todayFlowerSent: false,
    
    // 加载状态
    loading: true
  },

  onLoad(options) {
    console.log('个人主页加载:', options);
    if (options.userNum) {
      this.setData({ userNum: parseInt(options.userNum) });
      this.loadUserData();
      this.checkFlowerStatus();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'error'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  onShow() {
    console.log('个人主页显示');
    this.checkFlowerStatus();
  },

  // 加载用户数据
  async loadUserData() {
    try {
      this.setData({ loading: true });
      
      // 并行加载用户资料和择偶标准
      const [profileRes, preferenceRes] = await Promise.all([
        this.loadUserProfile(),
        this.loadMatePreference()
      ]);
      
      console.log('用户数据加载完成');
      
    } catch (error) {
      console.error('加载用户数据失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 加载用户资料
  async loadUserProfile() {
    try {
      // 调用API获取用户资料
      const response = await api.getUserProfile(this.data.userNum);
      
      if (response && response.code === 0 && response.data && response.data.length > 0) {
        const profile = response.data[0];
        this.setData({ userProfile: profile });
        
        // 设置页面标题
        wx.setNavigationBarTitle({
          title: profile.name + ' - 个人资料'
        });
        
        return profile;
      } else {
        throw new Error('用户资料不存在');
      }
      
    } catch (error) {
      console.error('加载用户资料失败:', error);
      throw error;
    }
  },

  // 加载择偶标准
  async loadMatePreference() {
    try {
      // 调用API获取择偶标准
      const response = await api.queryMatePreference(this.data.userNum);
      
      if (response && response.code === 0 && response.data && response.data.length > 0) {
        const preference = response.data[0];
        this.setData({ matePreference: preference });
        return preference;
      } else {
        // 如果没有择偶标准数据，使用默认值
        this.setData({ matePreference: null });
        return null;
      }
      
    } catch (error) {
      console.error('加载择偶标准失败:', error);
      throw error;
    }
  },


  // 检查送花状态
  checkFlowerStatus() {
    const { userNum } = this.data;
    const todayFlowerKey = `todayFlower_${util.formatDate(new Date())}`;
    const todayFlowerSent = wx.getStorageSync(todayFlowerKey) || {};
    
    this.setData({
      todayFlowerSent: todayFlowerSent[userNum] || false
    });
  },

  // Tab切换
  onTabChange(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ selectedTab: tab });
  },

  // 送花按钮点击
  async onSendFlower() {
    const { userNum, todayFlowerSent } = this.data;
    const currentUser = app.globalData.currentUser;
    
    if (todayFlowerSent) {
      wx.showToast({
        title: '今日已赠送',
        icon: 'none'
      });
      return;
    }
    
    // 检查登录状态
    if (!currentUser.isLogin) {
      await this.handleLogin();
    }
    
    try {
      wx.showLoading({ title: '送花中...' });
      
      // 调用送花API
      await api.sendFlower(currentUser.userNum, userNum);
      
      // 更新本地送花状态
      const todayFlowerKey = `todayFlower_${util.formatDate(new Date())}`;
      const todayFlowerData = wx.getStorageSync(todayFlowerKey) || {};
      todayFlowerData[userNum] = true;
      wx.setStorageSync(todayFlowerKey, todayFlowerData);
      
      this.setData({ todayFlowerSent: true });
      
      wx.showToast({
        title: '送花成功！',
        icon: 'success'
      });
      
    } catch (error) {
      console.error('送花失败:', error);
      wx.showToast({
        title: '送花失败',
        icon: 'error'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 处理登录
  async handleLogin() {
    try {
      // 先调用微信登录
      const code = await app.login();
      
      // 获取用户手机号授权
      await new Promise((resolve, reject) => {
        wx.showModal({
          title: '登录提示',
          content: '需要获取您的手机号来完成登录',
          confirmText: '立即登录',
          cancelText: '暂不登录',
          success: (res) => {
            if (res.confirm) {
              resolve();
            } else {
              reject(new Error('用户取消登录'));
            }
          }
        });
      });
      
      console.log('登录成功');
      
    } catch (error) {
      console.error('登录失败:', error);
      throw error;
    }
  },

  // 格式化年龄范围
  formatAgeRange(ageRange) {
    if (!ageRange) return '不限';
    return util.formatRange(ageRange.minAge, ageRange.maxAge, '岁');
  },

  // 格式化身高范围
  formatHeightRange(heightRange) {
    if (!heightRange) return '不限';
    return util.formatRange(heightRange.minHeight, heightRange.maxHeight, 'cm');
  },

  // 格式化体重范围
  formatWeightRange(weightRange) {
    if (!weightRange) return '不限';
    return util.formatRange(weightRange.minWeight, weightRange.maxWeight, '斤');
  },

  // 格式化收入范围
  formatIncomeRange(incomeRange) {
    if (!incomeRange) return '不限';
    return util.formatRange(incomeRange.minIncome, incomeRange.maxIncome, '万元');
  },

  // 格式化学历范围
  formatEducationRange(educationRange) {
    if (!educationRange) return '不限';
    if (educationRange.minEducation === educationRange.maxEducation) {
      return educationRange.minEducation;
    } else if (educationRange.minEducation && educationRange.maxEducation) {
      return `${educationRange.minEducation} - ${educationRange.maxEducation}`;
    } else if (educationRange.minEducation) {
      return `${educationRange.minEducation}及以上`;
    } else if (educationRange.maxEducation) {
      return `${educationRange.maxEducation}及以下`;
    } else {
      return '不限';
    }
  },

  // 分享功能
  onShareAppMessage() {
    const { userProfile } = this.data;
    return {
      title: `${userProfile.name}的个人资料 - 青鸟传信`,
      path: `/pages/profile/profile?userNum=${userProfile.userNum}`,
      imageUrl: userProfile.avatar
    };
  }
});